import api from '../api';

export default {
  namespace: 'userM',
  state: {
    currentUser: {
      // 当前用户信息
      roleModels: [], // 用户角色信息
    },
    userMenuData: [], // 当前用户的菜单数据
    mainActivePath: undefined, // 主功能活跃的路由地址缓存
  },
  effects: {
    // 验证密码
    *verifyPassWord({ payload }, { call }) {
      const response = yield call(api.user.verifyPassWord, payload);
      return response;
    },
    // 修改密码
    *updatePassWord({ payload }, { call }) {
      const response = yield call(api.user.updatePassWord, payload);
      return response;
    },
    // 重置密码
    *resetPassword({ payload }, { call }) {
      const response = yield call(api.user.resetPassword, payload);
      return response;
    },
    // 获得菜单
    *getMenu({ payload }, { call, put }) {
      const response = yield call(api.user.getMenu, payload);
      if (response && response.success) {
        yield put({
          type: 'save2',
          payload: { userMenuData: response.data },
        });
      }
      // 本地存储菜单信息
      return response;
    },
    // 获取登录用户信息
    *fetchCurrent({ payload }, { call, put }) {
      const response = yield call(api.user.queryCurrent, payload);
      console.log('3-user.js--', payload);
      if (response && response.success) {
        yield put({
          type: 'save2',
          payload: { currentUser: response.data },
        });
        // 存储用户所有的角色
        const roles = response.data?.roleModels?.map((item) => item.roleId);
        localStorage.setItem('roleIds', encodeURI(JSON.stringify(roles)));
        // 判断是否包含运营管理角色
        const isOperationsManage = response.data?.roleModels?.findIndex((item) => item.roleId === 'YYGL');
        console.log('4-user.js返回，', response.data.userId);
        localStorage.setItem('isOperationsManage', isOperationsManage > -1); // //判断是否包含运营管理角色
        localStorage.setItem('antd-pro-userId', response.data.userId); // 设置userId供其他接口使用
        localStorage.setItem('antd-pro-tenant', response.data.tenant);
        localStorage.setItem('antd-pro-superMan', response.data.superMan);
        localStorage.setItem('antd-pro-admin', response.data.admin); // 判断是否是租户管理员
        localStorage.setItem('antd-pro-tenantName', response.data.tenantName);
        return response.data;
      }
      console.log(response, '******getUser获取用户信息接口***登录失败********');
      return '登录失败';
    },
  },

  reducers: {
    // 保存主功能活跃的路由地址缓存参数mainActivePath
    saveParams(state, { payload }) {
      return { ...state, ...payload };
    },
    // 保存用户信息
    save2(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};
